import React, { useState, useEffect } from 'react';
import SimpleImageViewer from './SimpleImageViewer';
import TDCImageViewer from './TDCImageViewer';
import TDCAnalyzer from './TDCAnalyzer';
import TDCMarkersPanel from './TDCMarkersPanel';
import VesselExtractionViewer from './VesselExtractionViewer';
import ImageToolbar from './ImageToolbar';
import './ViewerLayout.css';

const ViewerLayout = ({ 
  dicomData, 
  processedImages, 
  currentTool, 
  onToolChange, 
  colorMap, 
  enableInterpolation, 
  enableInvert, 
  frameRange = { start: 1, end: 1 },
  onVesselMaskUpdate, 
  onTdcModeChange, 
  onVesselModeChange,
  processingMethod = 'normal',
  arterialInputPoint = null,
  onArterialInputPointChange,
  onTdcChartDataUpdate
}) => {
  const [activeView, setActiveView] = useState('original');
  const [tdcMode, setTdcMode] = useState(false);
  const [tdcMarkers, setTdcMarkers] = useState([]);
  const [tdcChartData, setTdcChartData] = useState([]);
  
  // 血管提取相关状态
  const [vesselMode, setVesselMode] = useState(false);
  const [vesselMask, setVesselMask] = useState(null);

  // 生成当前DICOM数据的唯一标识
  const getDicomSessionKey = () => {
    if (!dicomData) return null;
    
    // 使用序列实例UID和图像数量作为唯一标识
    const seriesUID = dicomData.seriesInstanceUID || 'unknown';
    const imageCount = dicomData.images?.length || 0;
    const firstImageTime = dicomData.images?.[0]?.acquisitionTime || 'unknown';
    
    return `tdc_markers_${seriesUID}_${imageCount}_${firstImageTime}`;
  };

  // 保存标记到本地存储
  const saveTdcMarkers = (markers) => {
    const sessionKey = getDicomSessionKey();
    if (sessionKey && markers.length > 0) {
      try {
        const markersData = {
          markers: markers,
          timestamp: Date.now(),
          dicomInfo: {
            seriesUID: dicomData?.seriesInstanceUID,
            imageCount: dicomData?.images?.length,
            patientName: dicomData?.metadata?.patientName || 'Unknown'
          }
        };
        localStorage.setItem(sessionKey, JSON.stringify(markersData));
        console.log(`TDC标记已保存: ${markers.length} 个标记`);
      } catch (error) {
        console.warn('保存TDC标记失败:', error);
      }
    }
  };

  // 从本地存储加载标记
  const loadTdcMarkers = () => {
    const sessionKey = getDicomSessionKey();
    if (sessionKey) {
      try {
        const savedData = localStorage.getItem(sessionKey);
        if (savedData) {
          const markersData = JSON.parse(savedData);
          if (markersData.markers && Array.isArray(markersData.markers)) {
            setTdcMarkers(markersData.markers);
            console.log(`TDC标记已恢复: ${markersData.markers.length} 个标记`);
            return markersData.markers.length > 0;
          }
        }
      } catch (error) {
        console.warn('加载TDC标记失败:', error);
      }
    }
    return false;
  };

  // 清理过期的标记数据（保留最近7天的数据）
  const cleanupOldMarkers = () => {
    try {
      const now = Date.now();
      const maxAge = 7 * 24 * 60 * 60 * 1000; // 7天
      
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && key.startsWith('tdc_markers_')) {
          const data = localStorage.getItem(key);
          if (data) {
            const markersData = JSON.parse(data);
            if (markersData.timestamp && (now - markersData.timestamp > maxAge)) {
              localStorage.removeItem(key);
              console.log(`清理过期TDC标记: ${key}`);
            }
          }
        }
      }
    } catch (error) {
      console.warn('清理过期标记失败:', error);
    }
  };

  // 在DICOM数据加载时清空所有分析数据
  useEffect(() => {
    if (dicomData && dicomData.images && dicomData.images.length > 1) {
      console.log('检测到新的DICOM数据，清空所有分析数据...');
      
      // 清理过期数据
      cleanupOldMarkers();
      
      // 清空当前的标记和状态，不恢复之前的数据
      setTdcMarkers([]);
      setVesselMask(null);
      
      // 退出特殊模式
      setTdcMode(false);
      setVesselMode(false);
      setActiveView('original'); // 重置到原始视图
      
      // 通知父组件清空血管mask
      if (onVesselMaskUpdate) {
        onVesselMaskUpdate(null);
      }
      
      // 通知父组件退出特殊模式
      if (onTdcModeChange) {
        onTdcModeChange(false);
      }
      if (onVesselModeChange) {
        onVesselModeChange(false);
      }
      
      console.log('所有分析数据已清空，准备开始新的分析');
    } else {
      // 如果没有DICOM数据，清空所有状态
      setTdcMarkers([]);
      setVesselMask(null);
      setTdcMode(false);
      setVesselMode(false);
      setActiveView('original');
    }
  }, [dicomData]);

  // 监听标记变化并自动保存
  useEffect(() => {
    if (tdcMarkers.length > 0) {
      saveTdcMarkers(tdcMarkers);
    }
  }, [tdcMarkers]);

  // 血管mask的清理逻辑已合并到上面的useEffect中

  const views = [
    {
      id: 'original',
      title: '原始图像',
      data: dicomData,
      type: 'dicom',
      enabled: !!dicomData
    },
    {
      id: 'ttp',
      title: 'TTP (Time To Peak)',
      data: processedImages.ttp ? { ...processedImages.ttp, colorMap } : null,
      type: 'processed',
      enabled: !!processedImages.ttp
    },
    {
      id: 'mtt',
      title: 'MTT (Mean Transit Time)',
      data: processedImages.mtt ? { ...processedImages.mtt, colorMap } : null,
      type: 'processed',
      enabled: !!processedImages.mtt
    },
    {
      id: 'ph',
      title: 'PH (Peak Height)',
      data: processedImages.ph ? { ...processedImages.ph, colorMap } : null,
      type: 'processed',
      enabled: !!processedImages.ph
    },
    {
      id: 'auc',
      title: 'AUC (Area Under Curve)',
      data: processedImages.auc ? { ...processedImages.auc, colorMap } : null,
      type: 'processed',
      enabled: !!processedImages.auc
    },
    {
      id: 'cbf',
      title: 'CBF (Cerebral Blood Flow)',
      data: processedImages.cbf ? { ...processedImages.cbf, colorMap } : null,
      type: 'processed',
      enabled: !!processedImages.cbf
    },
    {
      id: 'cbv',
      title: 'CBV (Cerebral Blood Volume)',
      data: processedImages.cbv ? { ...processedImages.cbv, colorMap } : null,
      type: 'processed',
      enabled: !!processedImages.cbv
    }
  ];

  const currentView = views.find(view => view.id === activeView);

  // 切换TDC模式
  const toggleTdcMode = () => {
    const newTdcMode = !tdcMode;
    setTdcMode(newTdcMode);
    
    // 通知App.js状态变化
    if (onTdcModeChange) {
      onTdcModeChange(newTdcMode);
    }
    
    if (newTdcMode) {
      // 进入TDC模式时，确保在原始图像视图
      setActiveView('original');
    }
  };

  // 手动清空所有标记
  const clearAllTdcMarkers = () => {
    if (tdcMarkers.length > 0) {
      if (window.confirm('确定要清空所有TDC标记吗？此操作无法撤销。')) {
        setTdcMarkers([]);
        setTdcChartData([]); // 同时清空图表数据
        // 也从本地存储中删除
        const sessionKey = getDicomSessionKey();
        if (sessionKey) {
          localStorage.removeItem(sessionKey);
          console.log('TDC标记已从存储中清除');
        }
      }
    }
  };

  // 处理TDC图表数据更新
  const handleTdcChartDataUpdate = (chartData) => {
    setTdcChartData(chartData);
    // 同时向上传递给App.js
    if (onTdcChartDataUpdate) {
      onTdcChartDataUpdate(chartData);
    }
  };

  // 处理标记变化
  const handleMarkersChange = (newMarkers) => {
    setTdcMarkers(newMarkers);
    // 当标记发生变化时，如果没有标记了，清空图表数据
    if (newMarkers.length === 0) {
      setTdcChartData([]);
    }
  };

  // 血管提取相关函数
  // 切换血管提取模式
  const toggleVesselMode = () => {
    const newVesselMode = !vesselMode;
    setVesselMode(newVesselMode);
    
    // 通知App.js状态变化
    if (onVesselModeChange) {
      onVesselModeChange(newVesselMode);
    }
    
    if (newVesselMode) {
      // 进入血管提取模式时，确保在原始图像视图，并退出TDC模式
      setActiveView('original');
      const newTdcMode = false;
      setTdcMode(newTdcMode);
      if (onTdcModeChange) {
        onTdcModeChange(newTdcMode);
      }
    }
  };

  // 生成血管mask会话key
  const getVesselMaskSessionKey = () => {
    if (!dicomData) return null;
    
    const seriesUID = dicomData.seriesInstanceUID || 'unknown';
    const imageCount = dicomData.images?.length || 0;
    const firstImageTime = dicomData.images?.[0]?.acquisitionTime || 'unknown';
    
    return `vessel_mask_${seriesUID}_${imageCount}_${firstImageTime}`;
  };

  // 保存血管mask到本地存储
  const saveVesselMask = (mask) => {
    const sessionKey = getVesselMaskSessionKey();
    if (sessionKey && mask) {
      try {
        const maskData = {
          mask: Array.from(mask.mask), // 转换为普通数组以便JSON序列化
          width: mask.width,
          height: mask.height,
          threshold: mask.threshold,
          timestamp: mask.timestamp,
          stats: mask.stats,
          dicomInfo: {
            seriesUID: dicomData?.seriesInstanceUID,
            imageCount: dicomData?.images?.length,
            patientName: dicomData?.metadata?.patientName || 'Unknown'
          }
        };
        localStorage.setItem(sessionKey, JSON.stringify(maskData));
        console.log('血管mask已保存:', mask.stats);
      } catch (error) {
        console.warn('保存血管mask失败:', error);
      }
    }
  };

  // 从本地存储加载血管mask
  const loadVesselMask = () => {
    const sessionKey = getVesselMaskSessionKey();
    if (sessionKey) {
      try {
        const savedData = localStorage.getItem(sessionKey);
        if (savedData) {
          const maskData = JSON.parse(savedData);
          // 重新转换为Uint8Array
          const restoredMask = {
            mask: new Uint8Array(maskData.mask),
            width: maskData.width,
            height: maskData.height,
            threshold: maskData.threshold,
            timestamp: maskData.timestamp,
            stats: maskData.stats
          };
          setVesselMask(restoredMask);
          console.log('血管mask已恢复:', restoredMask.stats);
          
          // 通知App.js更新当前血管mask
          if (onVesselMaskUpdate) {
            onVesselMaskUpdate(restoredMask);
          }
        }
      } catch (error) {
        console.warn('加载血管mask失败:', error);
      }
    }
  };

  // 处理血管mask生成
  const handleVesselMaskGenerated = (mask) => {
    setVesselMask(mask);
    saveVesselMask(mask);
    
    // 通知App.js更新当前血管mask
    if (onVesselMaskUpdate) {
      onVesselMaskUpdate(mask);
    }
    
    // 生成mask后可以选择退出血管提取模式
    if (window.confirm('血管mask已生成！是否退出血管提取模式返回原始视图？')) {
      const newVesselMode = false;
      setVesselMode(newVesselMode);
      if (onVesselModeChange) {
        onVesselModeChange(newVesselMode);
      }
    }
  };

  return (
    <div className={`viewer-layout ${tdcMode ? 'tdc-fullscreen' : ''} ${vesselMode ? 'vessel-fullscreen' : ''}`}>
      {/* 在TDC模式或血管提取模式下隐藏视图切换标签页 */}
      {!tdcMode && !vesselMode && (
        <div className="view-tabs">
          {views.map(view => (
            <button
              key={view.id}
              className={`view-tab ${activeView === view.id ? 'active' : ''} ${!view.enabled ? 'disabled' : ''}`}
              onClick={() => {
                if (view.enabled) {
                  setActiveView(view.id);
                  // 如果切换到非原始视图，退出TDC模式和血管提取模式
                  if (view.id !== 'original') {
                    if (tdcMode) {
                      setTdcMode(false);
                      if (onTdcModeChange) onTdcModeChange(false);
                    }
                    if (vesselMode) {
                      setVesselMode(false);
                      if (onVesselModeChange) onVesselModeChange(false);
                    }
                  }
                }
              }}
              disabled={!view.enabled}
            >
              <span className="tab-title">{view.title}</span>
              {!view.enabled && (
                <span className="tab-status">未处理</span>
              )}
              {view.enabled && view.type === 'processed' && (
                <span className="tab-status">已处理</span>
              )}
            </button>
          ))}
        </div>
      )}

      <div className="viewer-container">
        {currentView && currentView.enabled ? (
          <div className={`viewer-content ${tdcMode ? 'split-view' : ''} ${vesselMode ? 'vessel-view' : ''}`}>
            {vesselMode ? (
              // 血管提取模式
              <VesselExtractionViewer
                data={currentView.data}
                onMaskGenerated={handleVesselMaskGenerated}
                onExitVesselMode={toggleVesselMode}
              />
            ) : !tdcMode ? (
              // 普通单视图模式
              <>
                <ImageToolbar 
                  currentTool={currentTool} 
                  onToolChange={onToolChange}
                  processingMethod={processingMethod}
                />
                <SimpleImageViewer
                  key={`viewer-${currentView.id}`}
                  data={currentView.data}
                  type={currentView.type}
                  viewId={currentView.id}
                  currentTool={currentTool}
                  title={currentView.title}
                  enableInterpolation={enableInterpolation}
                  // TDC相关props
                  showTdcButton={currentView.id === 'original' && dicomData && dicomData.images && dicomData.images.length > 1}
                  tdcMode={tdcMode}
                  onToggleTdc={toggleTdcMode}
                  // 血管提取相关props
                  showVesselButton={currentView.id === 'original' && dicomData && dicomData.images && dicomData.images.length > 1}
                  vesselMode={vesselMode}
                  onToggleVessel={toggleVesselMode}
                  // 动脉输入点相关props - 只在原始图像视图中显示
                  processingMethod={processingMethod}
                  arterialInputPoint={currentView.id === 'original' ? arterialInputPoint : null}
                  onArterialInputPointChange={currentView.id === 'original' ? onArterialInputPointChange : null}
                />
              </>
            ) : (
              // TDC分割视图模式
              <div className="tdc-split-container">
                <div className="tdc-image-panel">
                  <div className="panel-header">
                    <h4>原始图像 - TDC标记</h4>
                    <div className="panel-info">
                      {dicomData.images.length} 帧图像
                      {tdcMarkers.length > 0 && (
                        <span className="markers-saved-tip">
                          | 📌 {tdcMarkers.length} 个标记已保存
                        </span>
                      )}
                    </div>
                    <button
                      className="exit-tdc-btn"
                      onClick={toggleTdcMode}
                      title="退出TDC分析模式，返回原始视图（标记将自动保存）"
                    >
                      <span className="exit-icon">←</span>
                      <span className="exit-text">返回原始视图</span>
                    </button>
                  </div>
                  <TDCImageViewer
                    data={currentView.data}
                    type={currentView.type}
                    viewId={currentView.id}
                    currentTool={currentTool}
                    title={currentView.title}
                    enableInterpolation={enableInterpolation}
                    markers={tdcMarkers}
                    onMarkersChange={handleMarkersChange}
                  />
                </div>
                
                <div className="tdc-chart-panel">
                  <TDCAnalyzer
                    dicomData={dicomData}
                    markers={tdcMarkers}
                    enableInvert={enableInvert}
                    frameRange={frameRange}
                    onChartDataUpdate={handleTdcChartDataUpdate}
                  />
                </div>
                
                <div className="tdc-markers-panel">
                  <TDCMarkersPanel
                    markers={tdcMarkers}
                    onMarkerUpdate={handleMarkersChange}
                    onClearAllMarkers={clearAllTdcMarkers}
                    chartData={tdcChartData}
                    dicomData={dicomData}
                    frameRange={frameRange}
                  />
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="empty-viewer">
            <div className="empty-content">
              <div className="empty-icon">📋</div>
              <h3>请加载DICOM序列</h3>
              <p>
                {activeView === 'original' 
                  ? '请在左侧面板中加载DICOM序列或演示数据'
                  : '请先加载图像并进行处理以查看此视图'
                }
              </p>
              {activeView !== 'original' && !dicomData && (
                <div className="empty-steps">
                  <div className="step">1. 加载DICOM图像序列</div>
                  <div className="step">2. 点击"开始处理"按钮</div>
                  <div className="step">3. 查看处理结果</div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* 在TDC模式下也隐藏底部信息栏 */}
      {!tdcMode && (
        <div className="view-info">
          <div className="view-description">
            {currentView?.id === 'original' && !tdcMode && (
              <span>显示原始DICOM图像序列，支持多帧浏览</span>
            )}
            {currentView?.id === 'original' && tdcMode && (
              <span>TDC分析模式 - 在左侧图像上添加标记点或区域，右侧查看时间-密度曲线</span>
            )}
            {currentView?.id === 'ttp' && (
              <span>Time To Peak - 显示每个像素达到峰值的时间映射</span>
            )}
            {currentView?.id === 'mtt' && (
              <span>Mean Transit Time - 显示造影剂平均通过时间映射</span>
            )}
            {currentView?.id === 'ph' && (
              <span>Peak Height - 显示信号峰值高度映射</span>
            )}
            {currentView?.id === 'auc' && (
              <span>Area Under Curve - 显示时间-信号曲线下面积映射</span>
            )}
            {currentView?.id === 'cbf' && (
              <span>Cerebral Blood Flow - 显示脑血流量映射 (ml/100g/min)</span>
            )}
            {currentView?.id === 'cbv' && (
              <span>Cerebral Blood Volume - 显示脑血容量映射 (ml/100g)</span>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default ViewerLayout; 